﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using CoreColution.Entity.Basics;
using CoreSolution.IService.Basics;
using CoreSolution.Tools.WebResult;
using CoreSolution.Vip.Model.Basics;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using CoreSolution.Tools.Extensions;
using CoreSolution.Vip.Manager;
using CoreColution.EntityDto.Basics;
using AutoMapper;
using CoreSolution.Tools;

namespace CoreSolution.Vip.Controllers
{
    [EnableCors("AllowAllOrigin")]
    [Route("api/UseInfo")]
    [Produces("application/json")]
    //[ApiController] 不能采用，不然action 就不能以对象形式接受参数
    public class UseInfoController : ControllerBase
    {
        private readonly IUserInfoServices _IUserInfoServices;

        public UseInfoController(IUserInfoServices iUserInfoServices)
        {
            _IUserInfoServices = iUserInfoServices;
            
        }

        #region 登录操作
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="loginInfo">登陆信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("DoLogin")]
        public async Task<JsonResult> DoLogin(UserLogin loginInfo)
        {
            if (string.IsNullOrEmpty(loginInfo.username))
            {
                return AjaxHelper.JsonResult(HttpStatusCode.BadRequest, "用户名不能为空");
            }

            if (string.IsNullOrEmpty(loginInfo.password))
            {
                return AjaxHelper.JsonResult(HttpStatusCode.BadRequest, "密码不能为空");
            }

            ////校验过程
            UserInfo user = new UserInfo();
            if (loginInfo.username.IsNumeric())
            {
                user = _IUserInfoServices.FirstOrDefault(t => t.PhoneNum == loginInfo.username);
                if (user == null)
                {
                    return AjaxHelper.JsonResult(HttpStatusCode.NotFound, "手机号不存在");
                }

                if (!user.IsPhoneNumConfirmed)
                {
                    return AjaxHelper.JsonResult(HttpStatusCode.NotFound, "请激活该账号");
                }
            }
            else
            {
                user = _IUserInfoServices.FirstOrDefault(t => t.UserName == loginInfo.username);
                if (user == null)
                {
                    return AjaxHelper.JsonResult(HttpStatusCode.NotFound, "账号不存在");
                }
            }
            
            ////判断密码
            if (loginInfo.password.ToMd5().ToUpper() == user.Password.ToUpper())
            {
                //获取已登录的信息,清除已登录用户
                var alreadytoken = await LoginManager.GetTokeByUserIdAsync(user.Id);

                if (!string.IsNullOrEmpty(alreadytoken))
                    await LoginManager.ClearRedisData(user.Id, alreadytoken);

                //设置Token
                string token = Guid.NewGuid().ToString();
                await LoginManager.LoginAsync(token, user.Id);


                var userInfo = new
                {
                    token = token
                };

                return AjaxHelper.JsonResult(HttpStatusCode.OK, "登陆成功", userInfo);
            }
            else
            {
                return AjaxHelper.JsonResult(HttpStatusCode.BadRequest, "密码错误");
            }
        }

        /// <summary>
        /// 退出登陆
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("OutLogin")]
        public async Task<JsonResult> OutLogin()
        {
            string token = HttpContext.Request.Headers["X-Token"];
            var userId = (await LoginManager.GetUserIdAsync(token)).GetValueOrDefault();

            //获取已登录的信息,清除已登录用户
            var alreadytoken = await LoginManager.GetTokeByUserIdAsync(userId);
            if (!string.IsNullOrEmpty(alreadytoken))
                await LoginManager.ClearRedisData(userId, alreadytoken);

            return AjaxHelper.JsonResult(HttpStatusCode.OK, "退出登陆");
        }
        
      
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="token">Token</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserInfo")]
        public async Task<JsonResult> GetUserInfo(string token)
        {
            var userId = await LoginManager.GetUserIdAsync(token);
            if (userId.HasValue)
            {
                var result = _IUserInfoServices.FirstOrDefault(t=>t.Id==userId.Value);
                return AjaxHelper.JsonResult(HttpStatusCode.OK, "成功", result);
            }
            else
            {
                return AjaxHelper.JsonResult(HttpStatusCode.BadRequest, "token失效");
            }
        }

        #endregion


        #region 后台操作
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserInfoList")]
        public async Task<JsonResult> GetUserInfoList(UserInfoSearch model)
        {
            var where = PredicateExtensions.True<UserInfo>();
            if (!string.IsNullOrEmpty(model.UserName))
            {
                where = where.And(x =>x.UserName.Contains(model.UserName));
            }

            if (!string.IsNullOrEmpty(model.Email))
            {
                where = where.And(x => x.Email.Contains(model.Email));
            }

            if (!string.IsNullOrEmpty(model.PhoneNum))
            {
                where = where.And(x => x.PhoneNum.Contains(model.PhoneNum));
            }

            if (model.UserType.HasValue)
            {
                var UserType = model.UserType.Value;
                where = where.And(x => x.UserType.Equals(UserType));
            }
            
            var UserInfo = _IUserInfoServices.Where(where).OrderByDesc(t=>t.CreateDate).Skip((model.PageIndex-1)*model.PageSize).Take(model.PageSize).ToList();

            return AjaxHelper.JsonResult(HttpStatusCode.OK, "获取成功", UserInfo);
        }

        /// <summary>
        /// 添加编辑用户
        /// </summary>
        /// <param name="model">实体类</param>
        /// <param name="TypeOper">操作:0.添加 1 编辑</param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddEditUserInfo")]
        public async Task<JsonResult> AddEditUserInfo(UserInfoDto model)
        {
            var data = Mapper.Map<UserInfo>(model);
            var Num = 0;
            var Msg = "";

            //默认都是通过的
            data.IsPhoneNumConfirmed = true;
            data.IsEmailConfirmed = true;

            if (model.TypeOper == 0)
            {
                data.Id = Guid.NewGuid();
                data.Password ="111111".ToMd5().ToString();
                Num =_IUserInfoServices.Add(data);
                Msg = "添加成功";
            }
            else
            {
                var userInfoDefault=_IUserInfoServices.FirstOrDefault(t => t.Id == model.Id);
                data.Password = userInfoDefault.Password;
                Num =_IUserInfoServices.Update(data);
                Msg = "修改成功";
            }
            _IUserInfoServices.SaveChange(Num);
           return AjaxHelper.JsonResult(HttpStatusCode.OK, Msg);
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="model">实体类</param>
        /// <param name="TypeOper">操作:0.添加 1 编辑</param>
        /// <returns></returns>
        [HttpPost]
        [Route("DeleteUserInfo")]
        public async Task<JsonResult> DeleteUserInfo(Guid Id)
        {
             var num=_IUserInfoServices.Delete(Id);
            _IUserInfoServices.SaveChange(num);
            return AjaxHelper.JsonResult(HttpStatusCode.OK, "删除成功");
        }

        /// <summary>
        /// 获取单条用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserInfoSingle")]
        public async Task<JsonResult> GetUserInfoSingle(Guid Id)
        {
           var userInfo=_IUserInfoServices.FirstOrDefault(t => t.Id == Id);
            return AjaxHelper.JsonResult(HttpStatusCode.OK, "成功", userInfo);
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ResetPassWord")]
        public async Task<JsonResult> ResetPassWord(UserResetPassword model)
        {
            var userInfo = _IUserInfoServices.FirstOrDefault(t => t.Id == model.Id);

            var passmd5=model.PassWord.ToMd5().ToString();
            var num=_IUserInfoServices.Update(t => new UserInfo() { Id = model.Id, Password = passmd5 });
            _IUserInfoServices.SaveChange(num);

            return AjaxHelper.JsonResult(HttpStatusCode.OK, "成功");
        }

        #endregion
        
    }
}